# -*- coding:utf-8 -*-

from config import Config
from app import db
from app.models.business import Car_Pictures as CP
import base64
from qiniu import Auth
from qiniu.services.storage.bucket import BucketManager
from flask import current_app
from task import cly


config = Config()
bucket = config.QINIU_BUCKET_NAME
auth = Auth(config.QINIU_ACCESS_KEY, config.QINIU_SECRET_KEY)
bm = BucketManager(auth)

@cly.task
def delete_after_days(pics, days):
	if isinstance(pics, list):
		for pic in pics:
			bm.delete_after_days(bucket, pic, str(days))
	else:	
		bm.delete_after_days(bucket, pics, str(days))
	return

@cly.task
def qiniu_delete(pic):
	bm.delete(bucket, pic)
	return

@cly.task
def qiniu_batch_delete(pics):
	if not isinstance(pics, list):
		raise TypeError, 'a list is required'
	options = []
	for pic in pics:
		entry = '%s:%s'%(bucket, pic)
		encodedEntryURI = base64.encodestring(entry)
		options.append('/delete/'+encodedEntryURI)
	bm.batch(options)
	return

def save_car_picture(pictures, car_id):
	for k, v in pictures.items():
		pt = int(k)
		pics = []
		for pic in v:
			cp = CP(car_id=car_id, url=pic, picture_type=pt)
			db.session.add(cp)
			pics.append(pic)
	db.session.commit()
	delete_after_days.delay(pics, '0')		
	return

def delete_car_picture(del_pictures, car_id):
	pics = []
	for k, v in del_pictures.items():
		pt = int(k)
		for pic in v:
			pics.append(pic)
			cp = CP.query.filter_by(car_id=car_id, url=pic, picture_type=pt).first()
			db.session.delete(cp)
	db.session.commit()
	qiniu_batch_delete.delay(pics)
	return

